'use strict';

const usepay = require('use-pay');

const createConfig = require('uni-config-center');
const usepayConfig = createConfig({
	pluginId: 'use-pay'
});
const uniConfig = createConfig({
	pluginId: 'uni-id'
});

exports.main = async (event, context) => {
	//event为客户端上传的参数

	const res = {
		code: 200,
		msg: '',
		datas: {}
	}

	// path 默认格式为 /wxpay-transfers
	const paths = event.path.split('-');
	const key = paths[0].replace('/', '');

	if (paths.length !== 2) {
		res.msg = '路由错误';
		res.code = 400;
		return res;
	}

	try {
		if (!utils.hasOwnProperty(key)) {
			res.msg = '路由不合法';
			res.code = 400;
			return res;
		}

		if (!utils[key].hasOwnProperty(paths[1])) {
			res.msg = '路由不存在';
			res.code = 400;
			return res;
		}

		res.datas = await utils[key][paths[1]](event.body);
	} catch (e) {
		res.msg = e.message;
		res.code = 500;
	}

	//返回数据给客户端
	return res
};


/**
 * 微信支付、微信公众号
 * 
 * 处理需要固定 ip 的接口场景
 */
const utils = {
	// 微信支付
	wxpay: {
		// 企业付款到零钱
		transfers: async function(req) {
			if (typeof req === 'string') req = JSON.parse(req);

			const config = {
				appid: usepayConfig.config("wxpay.appid"),
				mchid: usepayConfig.config("wxpay.mchid"),
				partnerKey: usepayConfig.config("wxpay.partnerKey"),
				pfx: usepay.fs.readFileSync(usepay.path.resolve(__dirname, 'cert/wxpay/apiclient_cert.p12'))
			}

			const api = new usepay.tenpay(config, true);

			const result = await api.transfers({
				partner_trade_no: req.trade_no,
				openid: req.openid,
				re_user_name: req.truename || '',
				check_name: req.check_name,		// 是否校验实名合法性 NO_CHECK、FORCE_CHECK、OPTION_CHECK
				amount: req.amount,
				desc: req.desc
			});
			
			return result;
		},
		// 查询企业付款到零钱
		transfersQuery: async function(req) {
			if (typeof req === 'string') req = JSON.parse(req);
			
			
			const config = {
				appid: usepayConfig.config("wxpay.appid"),
				mchid: usepayConfig.config("wxpay.mchid"),
				partnerKey: usepayConfig.config("wxpay.partnerKey"),
				pfx: usepay.fs.readFileSync(usepay.path.resolve(__dirname, 'cert/wxpay/apiclient_cert.p12'))
			}
			
			const api = new usepay.tenpay(config, true);
			
			const result = await api.transfersQuery({
				partner_trade_no: req.trade_no
			});
			
			return result;
		}
	},
	// 微信公众号
	wxapi: {
		// 获取 access_token
		token: async function() {
			const appid = uniConfig.config('h5-weixin.oauth.weixin.appid');
			const appsecret = uniConfig.config('h5-weixin.oauth.weixin.appsecret');

			const url =
				`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`;

			const res = await http.get(url);

			if (res.access_token) {
				// 提前 5分钟过期
				res.expires_time = Date.now() + ((res.expires_in - 5 * 60) * 1000)
			}

			return res;
		}
	}
}


/**
 * http reqeust
 */
const http = {
	curl: async function(url, req = {
		method: 'get'
	}) {
		const res = await uniCloud.httpclient.request(url, {
			method: req.method,
			data: req.data,
			contentType: 'json',
			dataType: 'json'
		});

		return res;
	},
	get: async function(url) {
		const res = await this.curl(url);

		return res.data;
	},
	post: async function(url, data) {
		const res = await this.curl(url, {
			method: 'post',
			data: data
		});

		return res.data;
	}
}
